from rest_framework.permissions import IsAuthenticated
from django.db import transaction
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.decorators import api_view
from utils.base import BasePageNumberPagination
from apps.suites.filters import SuiteFilter, CrontabTaskFilter
from apps.suites.models import Suite, CrontabTask
from apps.suites.serializers import SuiteSerializer, CrontabTaskSerializer
from utils.base_view import BaseModelViewSet
from core.run_suite import run_suite


class SuiteViewSet(BaseModelViewSet):
    serializer_class = SuiteSerializer
    queryset = Suite.objects.all()
    permission_classes = [IsAuthenticated]
    pagination_class = BasePageNumberPagination
    filterset_class = SuiteFilter


class CrontabTaskView(BaseModelViewSet):
    queryset = CrontabTask.objects.all()
    serializer_class = CrontabTaskSerializer
    permission_classes = [IsAuthenticated]
    pagination_class = BasePageNumberPagination
    filterset_class = CrontabTaskFilter

    def perform_destroy(self, instance):
        with transaction.atomic():
            pt = instance.periodic_task
            instance.delete()
            if pt:
                pt.delete()


@api_view(['POST'])
def run_suite_case(request: Request):
    env_id = request.data.get('env_id')
    suite_id = request.data.get('suite_id')
    run_suite.delay(env_id, suite_id, request.user.id)
    return Response(data='执行完成', status=200)
